import getDeviceInfo from './deviceInfo'

// 传入要复制内容的dom节点
export const copy = (data) => {
  // 创建一个input
  var inputEl = document.createElement('input')
  // 设置为readonly 防止在ios系统中闪屏
  inputEl.setAttribute('readonly', '')
  // 把要复制的文本赋给input
  inputEl.value = data
  // 把input添加到body中
  document.body.appendChild(inputEl)
  // 选中全部文本 两个方法功能相同，为了兼容浏览器
  inputEl.select()
  inputEl.setSelectionRange(0, data.length)
  // 执行浏览器复制命令
  document.execCommand('Copy')
  // 移除input
  inputEl.remove()
}

// 位数随机数
export const getRandom = (digit) => {
  return Math.floor(
    (Math.random() + Math.floor(Math.random() * 9 + 1)) *
      Math.pow(10, digit - 1)
  )
}

// 指定范围内的随机数
export const getRandomNum = (start, end, fixed = 2) => {
  let differ = end - start
  let random = Math.random()
  return (start + differ * random).toFixed(fixed)
}

// 给url添加参数
export const addQuery = (url, name, value) => {
  let mark = '?'
  if (url.indexOf('?') !== -1) {
    mark = '&'
  }
  return url + mark + name + '=' + value
}

// 给url删除参数
export function urlDelP(url, name) {
  var urlArr = url.split('?')
  if (urlArr.length > 1 && urlArr[1].indexOf(name) > -1) {
    var query = urlArr[1]
    var obj = {}
    var arr = query.split('&')
    for (var i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split('=')
      obj[arr[i][0]] = arr[i][1]
    }
    delete obj[name]
    var urlte =
      urlArr[0] +
      '?' +
      JSON.stringify(obj)
        .replace(/[\"\{\}]/g, '')
        .replace(/\:/g, '=')
        .replace(/\,/g, '&')
    return urlte
  } else {
    return url
  }
}

// 重置数据
export const resetData = (target, pointName, pointVal, propertyName, value) => {
  let idx = target.findIndex((item) => {
    return item[pointName] === pointVal
  })
  Vue.set(target[idx], propertyName, value)
}

// 删除数据
export const delData = (target, pointName, pointVal) => {
  let idx = target.findIndex((item) => {
    return item[pointName] === pointVal
  })
  if (idx > -1) {
    target.splice(idx, 1)
  }
}

// 返回不刷新 针对低版本 ios
export const backRefresh = () => {
  if (getDeviceInfo().isIOS) {
    let isPageHide = false
    window.addEventListener('pageshow', function() {
      if (isPageHide) {
        window.location.reload()
      }
    })
    window.addEventListener('pagehide', function() {
      isPageHide = true
    })
  }
}

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行，false 表非立即执行
 */

export const debounce = (func, wait, immediate) => {
  let timeout
  return function() {
    let context = this
    let args = arguments

    if (timeout) clearTimeout(timeout)
    if (immediate) {
      var callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timeout = setTimeout(function() {
        func.apply(context, args)
      }, wait)
    }
  }
}

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 */

export const throttle = (func, wait) => {
  let timer

  return () => {
    if (timer) {
      return
    }

    timer = setTimeout(() => {
      func()
      timer = null
    }, wait)
  }
}

export const smoothScroll = (el, fromTop = 0, defaultStep = 50) => {
  let total = el.offsetTop + fromTop
  let distance = document.documentElement.scrollTop || document.body.scrollTop
  // 平滑滚动，时长500ms，每10ms一跳，共50跳
  let step = total / defaultStep
  if (total > distance) {
    smoothDown()
  } else {
    let newTotal = distance - total
    step = newTotal / 50
    smoothUp()
  }

  function smoothDown() {
    if (distance < total) {
      distance += step
      document.body.scrollTop = distance
      document.documentElement.scrollTop = distance
      setTimeout(smoothDown, 10)
    } else {
      document.body.scrollTop = total
      document.documentElement.scrollTop = total
    }
  }

  function smoothUp() {
    if (distance > total) {
      distance -= step
      document.body.scrollTop = distance
      document.documentElement.scrollTop = distance
      setTimeout(smoothUp, 10)
    } else {
      document.body.scrollTop = total
      document.documentElement.scrollTop = total
    }
  }
}
